import React,{useEffect, useState} from 'react';
import { Modal, Form, Input, Select, Checkbox } from 'antd';
import { EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import RoleListComponent from './RoleListComponent';
import ParentOrgListComponent from './ParentOrgListComponent';
import { FormInstance } from 'antd/lib/form';
import { TableListItem } from '../data.d';
// import styles from '../index.less';

interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: (values: TableListItem) => void;
  values: TableListItem;
}

const { Option } = Select;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

const validateMessages = {
  // required: '${label} is required!',
  types: {
    email: '${label}格式不正确!',
    // number: '${label}格式不正确!',
  },
  // number: {
  //   range: '${label} must be between ${min} and ${max}',
  // },
};

const AddUserForm: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;
  const [form] = Form.useForm();
  const [orgIdDisabled, handleOrgIdDisabled] = useState<boolean>(true);
  const [disabled, handleDisabled] = useState<boolean>(true);//所属角色是否可用，根据所属机构
  const [orgId, setOrgId] = useState<number>(10000);//【所属角色】与【所属机构】联动
  const [roleId, setRoleId] = useState<number>(10000);//【所属角色】与【所属机构】联动
  
  const [userStateDisabled, handleUserStateDisabled] = useState<boolean>(true);

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as TableListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  useEffect(() => {
    if(modalVisible){
      if(values.id){//编辑
        console.log(values)
        form.setFieldsValue({
          id:values.id,
          nickname: values.nickname,
          username: values.username,
          password: values.password,
          original_password:values.password,
          roleId: values.roleId,
          orgId: values.orgId,
          userState: values.userState,
          phone: values.phone,
          email: values.email,
          systemDefaultFlag:values.scope=="SYSTEM"?true:false,
        });
        setOrgId(values.orgId);
        // setRoleId(values.roleId);
        // console.log(values.roleId)
        if(values.scope == "SYSTEM" && JSON.parse(localStorage.getItem("user")).orgId != 10000){
          handleOrgIdDisabled(true);
          handleDisabled(true);
          handleUserStateDisabled(true);
        }else{
          handleOrgIdDisabled(false);
          handleDisabled(false);
          handleUserStateDisabled(false);
        }
        
      }else{//新建
        form.resetFields();
        handleOrgIdDisabled(false);
        handleDisabled(true);
        handleUserStateDisabled(false);
      }
    }
  },[modalVisible]);

  const passwordValidator = (rule, value, callback) => {
    if(form.getFieldValue("original_password") == value){
      callback();
    }else{
      var reg = new RegExp(/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[.~!@#$%^&*_-])[\da-zA-Z.~!@#$%^&*_-]{8,16}$/);
      if(!reg.exec(value)){
        callback("密码为8到16位，且同时包含字母数字和特殊字符（.~!@#$%^&*_-）");
      }else{
        callback();
      }
    }
  }

  const onSelectChange =(e:Event)=>{
    form.setFieldsValue({systemDefaultFlag:e.target.checked});
  }

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item name="original_password" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          label="用户名"
          name="nickname"
          rules={[
            { required: values.id?false:true, max: 16, min:2, whitespace: true},
          ]}
        >
          {values?.id?(
              values.nickname
            ):(
              <Input placeholder="请输入用户名"/> 
            )
          }
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[
            { required: true,
            },{
              validator: passwordValidator
          }
          ]}
        >
          <Input.Password
            placeholder="请输入密码"
            iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
            autoComplete="new-password"
          />
        </Form.Item>
        <Form.Item name="orgId" label="所属机构" rules={[{ required: true }]}>
            <ParentOrgListComponent
              disabled={orgIdDisabled} 
              defaultvalue={values?values.orgId:-1}
              type="orgId"
              selectChange={(value,orgId) => {
                form.setFieldsValue({"orgId": value,"roleId":null});
                setOrgId(value);
                if(value){
                  handleDisabled(false);
                }else{
                  handleDisabled(true);
                }
              }}
              >
            </ParentOrgListComponent>
        </Form.Item>
        <Form.Item name="roleId" label="所属角色" rules={[{ required: true }]}>
          <RoleListComponent
            init={true}
            disabled={disabled}
            value=""
            defaultValue={values?.roleName} 
            selector={orgId}
            selectChange={(value) => {
              form.setFieldsValue({"roleId":value});
            }}>
          </RoleListComponent>
        </Form.Item>
        <Form.Item
          name="userState"
          label="账号状态"
          rules={[{ required: true }]}
        >
          <Select disabled={userStateDisabled} placeholder="请选择状态" allowClear>
            <Option value="ENABLE">启用</Option>
            <Option value="DISABLE">停用</Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="username"
          label="真实姓名"
          rules={[
            { max: 16, whitespace: true },
          ]}
        >
          <Input placeholder="请输入用户真实姓名"/>
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { type: 'email' }
          ]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机号"
          rules={[
            { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的手机号'},
          ]}
        >
          <Input placeholder="请输入手机号"/>
        </Form.Item>
        <Form.Item
          name="systemDefaultFlag"
          label="系统用户"
          style={{display:JSON.parse(localStorage.getItem("user")).orgId === 10000?"flex":"none"}}
        >
          <Checkbox defaultChecked={values?.scope=="SYSTEM"?true:false} onChange={onSelectChange}></Checkbox>
        </Form.Item>
      </>
    );
  };
  return (
    <Modal 
      destroyOnClose 
      title={values?"编辑用户":"添加用户"} 
      visible={modalVisible} 
      {...modalFooter} 
      centered
      >
      <Form 
        {...layout} 
        ref={formRef} 
        form={form}
        onFinish={handleFinish}
        validateMessages={validateMessages}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default AddUserForm;
